<?php
/**
 * Created by PhpStorm.
 * User: George
 * Date: 2017/9/25
 * Time: 11:06
 */

namespace AdminBundle\Task;


use AdminBundle\Entity\LogRoomJoined;

/**
 * 大群，100人以上群
 * 响应包体格式
 * 说明: 返回微信群对应的二维码(图片[jpg,png,gif]),如微信号在服务端被禁用则不返回对应数据.
 * name: 群名字
 * qrcode: 二维码下载地址
 * id:群唯一ID
 * count: 当前群内成员数量
 * status: 1表示位40人以下群，2表示40-100人群，3表示100-500人群，0表示暴力拉取的群。当前默认值为0
 * {"code":0,"msg":"ok","time":1482653499,"data":{"name":"群名字1","qrcode":"二维码下载地址http:\/\/admin.bjtwtx.com\/upload\\2016\\12\\19\\5788f7e6c468ec5cf0731ec4098f14bb.jpeg","id":"群ID","count":0,"status":0}}
 * 马甲号入群的二维码
 * 获取马甲号入群的二维码
 * Class QrcodeJoinRoomTask
 * @package AdminBundle\Task
 */
class QrcodeInviteRoomTask extends Task
{
    const ROOM_GT_100 = 3;        // 3表示100-500人群
    const SOURCE_TYPE_LABOUR = 2; // 2:营销好友


    public function jsonTask()
    {
        // 获取联系人
        $user_id = $this->task->getMethod();
        // 获取当前用户进入的群
        $room = $this->getRoom($user_id, self::ROOM_GT_100);
        if (empty($room)) {
            // 失败
            return null;
        }

        $contacts = $this->getContacts($user_id, self::SOURCE_TYPE_LABOUR, $room['note']);

        if (empty($contacts)) {
            // 失败
            return null;
        }
        $friends = [];
        foreach ($contacts as $contact) {
            $friends[] = [
                'nickname' => $contact['nickname'],
                'username' => $contact['userName'],
                'mobile' => $contact['mobile']
            ];
        }

        $this->logRoomJoined($contacts, $room);

        return $this->httpJson(null, [
            'name' => $room['name'],
            'qrcode' => $room['qrcode'],
            'friends' => $friends
        ]);
    }

    /**
     * 获取当前用户在第一步进入的群
     * @param $user_id
     * @param int $count
     */
    private function getRoom($user_id, $type, $count = 1)
    {
        $rooms = $this->em->getRepository('AdminBundle:BaseWebchatUser')->lastRoomByUserId($user_id, $type, $count);
        if ($rooms == null)
            return [];
        return $rooms[0];
    }

    /**
     * 根据微信号选择营销好友加入群
     * 规则：随机
     * @return array
     */
    private function getContacts($user_id, $source_type, $tags, $count = 50)
    {
        $friends = $this->em->getRepository('AdminBundle:BaseWebchatMember')->labourJoinRoom($user_id, $source_type, $tags, $count);
        if ($friends == null)
            return [];
        return $friends;
    }

    /**
     * 执行数据库操作
     * @param $em
     */
    public function logRoomJoined($contacts, $room)
    {

        if (empty($contacts))
            return;

        $em = $this->em;
        foreach ($contacts as $contact) {
            $logRoomJoined = new LogRoomJoined();

            $logRoomJoined->setCtime(new \DateTime())
                ->setWebchatId($this->task->getMethod())
                ->setWebchatUsername($this->task->getWebchatUsername())
                ->setMemberUserId($contact['id'])
                ->setRoomId($room['id'])
                ->setRoomName($room['name'])
                ->setRoomTags('')
                ->setRoomType($room['status'])
                ->setStatus(1);

            $em->persist($logRoomJoined);
        }
        $em->flush();
    }
}